package net.zio.kamenriderzioaddon.ridersystem;

import net.minecraft.ChatFormatting;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.zio.kamenriderzioaddon.enums.HenshinState;
import net.zio.kamenriderzioaddon.ridersystem.data.PlayerDataManager;
import net.zio.kamenriderzioaddon.ridersystem.registry.AwakeningConfig;
import net.zio.kamenriderzioaddon.ridersystem.registry.BaseRiderConfig;
import net.zio.kamenriderzioaddon.ridersystem.registry.FullRiderConfig;
import net.zio.kamenriderzioaddon.ridersystem.registry.RiderConfigRegistry;
import net.zio.kamenriderzioaddon.ridersystem.util.HenshinUtils;

import java.util.Map;

/**
 * 骑士管理器
 *
 * @author QianYunYi
 */
public class HenshinManager {
    public static final String PERSISTENT_TAG = "KamenRiderHenshinData";

    /**
     * 执行变身逻辑（状态机实现）
     *
     * @param entity 实体
     */
    public void executeHenshin(LivingEntity entity) {
        // 非玩家实体不处理
        if (!(entity instanceof Player player)) return;
        // 下蹲状态获取
        boolean isCrouching = player.isCrouching();
        // 获取玩家数据管理器
        PlayerDataManager dataManager = PlayerDataManager.get(player);
        // 获取玩家当前状态
        HenshinState currentState = dataManager.getCurrentState();
        //获取当前变身的骑士名称
        String activeRiderName = dataManager.getActiveRiderName();
        //获取当前变身的强化骑士名称
        String activeAwakeningName = dataManager.getActiveAwakeningName();
        //获取当前变身的骑士配置
        BaseRiderConfig baseConfig = activeRiderName != null ?
                RiderConfigRegistry.getConfig(activeRiderName) : null;
        //获取当前变身的强化骑士配置
        FullRiderConfig fullConfig = baseConfig instanceof FullRiderConfig ?
                (FullRiderConfig) baseConfig : null;
        //获取当前强化骑士配置
        AwakeningConfig awakeningConfig = fullConfig != null && activeAwakeningName != null ?
                fullConfig.getAwakeningConfig(activeAwakeningName) : null;

        switch (currentState) {

            //未变身时
            case INACTIVE:
                if(!dataManager.isHenshining()) {
                    handleInactiveState(player, isCrouching, PlayerDataManager.get(player));
                }
                break;

            //待机状态
            case STANDBY:
                if(!dataManager.isHenshining()) {
                    handleStandbyState(player, isCrouching, baseConfig, fullConfig, awakeningConfig,PlayerDataManager.get(player));
                }
                break;

            //变身状态
            case ACTIVE:
                if(!dataManager.isHenshining()) {
                    handleActiveState(player, isCrouching, baseConfig, fullConfig, dataManager,awakeningConfig,PlayerDataManager.get(player));
                }
                break;

            //二阶待机状态
            case STANDBY_AWAKENING:
                if(!dataManager.isHenshining()) {
                    handleStandbyAwakening(player, isCrouching, baseConfig, fullConfig, awakeningConfig);
                }
                break;

            //二阶变身状态
            case ACTIVE_AWAKENING:
                if(!dataManager.isHenshining()) {
                    handleActiveAwakening(player, isCrouching, baseConfig, fullConfig, awakeningConfig);
                }
                break;

            //未知状态
            default:
                HenshinUtils.sendMessage(player, "未知变身状态", ChatFormatting.RED);
                break;
        }
    }

    /**
     * 处理未变身状态
     */
    private void handleInactiveState(Player player, boolean isCrouching, PlayerDataManager dataManager) {
        // 优先检查强化形态
        if (tryAwakeningHenshin(player, isCrouching,dataManager)) {
            return;
        }

        // 然后检查基础骑士
        for (Map.Entry<String, BaseRiderConfig> entry : RiderConfigRegistry.getAllConfigs().entrySet()) {
            BaseRiderConfig config = entry.getValue();
            if (config.canTransform(player)) {
                if (isCrouching) {
                    // 快速变身
                    if (config instanceof FullRiderConfig) {
                        if (HenshinUtils.isFullyEquipped(player, config.getFullArmorSet())||isWearingBelt(player,config.getRiderName())){
                            if (config instanceof FullRiderConfig){
                                ((FullRiderConfig) config).handleDeactivation(player);
                            }
                        } else {
                            ((FullRiderConfig) config).handleQuickTransformation(player);
                        }
                    }
                } else {
                    // 进入待机状态
                    if (config instanceof FullRiderConfig) {
                        ((FullRiderConfig) config).enterStandbyState(player);
                    }
                }
                return;
            }
        }
    }

    /**
     * 尝试进行强化形态变身
     *
     * @return 如果成功处理强化形态变身，返回 true；否则返回 false
     */
    private boolean tryAwakeningHenshin(Player player, boolean isCrouching, PlayerDataManager dataManager) {
        // 遍历所有骑士配置
        for (Map.Entry<String, BaseRiderConfig> entry : RiderConfigRegistry.getAllConfigs().entrySet()) {
            BaseRiderConfig config = entry.getValue();
            // 只处理全形态配置
            if (config instanceof FullRiderConfig fullConfig) {
                // 检查每个强化形态
                for (AwakeningConfig awakeningConfig : fullConfig.getAwakeningConfigs().values()) {
                    // 检查是否符合强化形态变身条件
                    if (awakeningConfig.canTransform(player)) {
                        if (isCrouching) {
                            if (HenshinUtils.isFullyEquipped(player, awakeningConfig.getArmorSet())||isWearingBelt(player,awakeningConfig.getName())){
                                awakeningConfig.handleAwakeningDeactivation(player,fullConfig);
                            } else {
                                // 强化形态快速变身
                                awakeningConfig.handleQuickTransformation(player, fullConfig);
                            }

                        } else {
                            // 进入强化形态待机状态
                            awakeningConfig.handleStandbyAwakening(player, fullConfig);
                            // 设置当前强化形态名称
                            dataManager.setActiveAwakeningName(awakeningConfig.getName());
                            // 保存数据
                            dataManager.saveToPlayer(player);
                            dataManager.sync(player);
                        }
                        return true; // 已处理，返回
                    }
                }
            }
        }
        return false; // 没有找到符合条件的强化形态
    }

    /**
     * 处理待机状态
     */
    private void handleStandbyState(Player player, boolean isCrouching, BaseRiderConfig config, FullRiderConfig fullConfig,AwakeningConfig awakeningConfig,PlayerDataManager dataManager) {
        if (config == null) {
            HenshinUtils.sendMessage(player, "错误：未找到基础骑士配置", ChatFormatting.RED);
            return;
        }

        if (isCrouching) {
            // 解除变身
            if (config instanceof FullRiderConfig) {
                ((FullRiderConfig) config).handleDeactivation(player);
            }
        } else if (tryAwakeningHenshin(player, isCrouching,dataManager)){
            if(!player.getItemBySlot(EquipmentSlot.OFFHAND).isEmpty()) {
                //调用强化形态待机判断
                awakeningConfig.handleStandbyAwakening(player, fullConfig);
            }
        } else {
            // 完成基础变身
            if (config instanceof FullRiderConfig) {
                ((FullRiderConfig) config).handleHenshin(player);
            }
        }
    }

    /**
     * 处理变身状态
     */
    private void handleActiveState(Player player, boolean isCrouching,
                                   BaseRiderConfig baseConfig, FullRiderConfig fullConfig,
                                   PlayerDataManager data, AwakeningConfig awakeningConfig,PlayerDataManager dataManager) {
        if (baseConfig == null) {
            HenshinUtils.sendMessage(player, "错误：未找到基础骑士配置", ChatFormatting.RED);
            return;
        }
        if(!dataManager.isHenshining()) {
            if (isCrouching) {
                if (tryAwakeningHenshin(player, isCrouching,dataManager)) {
                    return;
                } else if (fullConfig != null) {// 解除基础变身
                        fullConfig.handleDeactivation(player);
                    }
            } else if (tryAwakeningHenshin(player, isCrouching,dataManager)){
                return;
            }
        }
    }

    /**
     * 处理强化形态待机状态
     */
    private void handleStandbyAwakening(Player player, boolean isCrouching,
                                        BaseRiderConfig baseConfig, FullRiderConfig fullConfig,
                                        AwakeningConfig awakeningConfig) {
        if (baseConfig == null || fullConfig == null || awakeningConfig == null) {
            HenshinUtils.sendMessage(player, "错误：强化形态配置缺失", ChatFormatting.RED);
            return;
        }

        if (isCrouching) {
            // 取消强化变身
            awakeningConfig.handleAwakeningDeactivation(player, fullConfig);
        } else {
            // 检查玩家是否符合强化形态变身条件
            // 执行强化变身
            if (awakeningConfig.getBehavior() != null) {
                awakeningConfig.getBehavior().handleAwakeningHenshin(player, fullConfig, awakeningConfig);
            }
        }
    }


    /**
     * 处理强化形态变身状态
     */
    private void handleActiveAwakening(Player player, boolean isCrouching,
                                       BaseRiderConfig baseConfig, FullRiderConfig fullConfig,
                                       AwakeningConfig awakeningConfig) {
        if (awakeningConfig == null || fullConfig == null) {
            HenshinUtils.sendMessage(player, "错误：强化形态配置异常", ChatFormatting.RED);
            forceDeactivateAll(player);
            return;
        }

        if (isCrouching) {
            // 解除强化形态，恢复基础形态
            if (awakeningConfig.getBehavior() != null) {
                awakeningConfig.getBehavior().handleAwakeningDeactivation(player, fullConfig, awakeningConfig);

                // 更新玩家数据
                PlayerDataManager data = PlayerDataManager.get(player);
                data.setActiveAwakeningName(""); // 清除强化形态名称
            }
        }
    }

    /**
     * 检查玩家是否处于变身状态
     */
    public boolean isPlayerTransformed(Player player) {
        PlayerDataManager data = PlayerDataManager.get(player);
        return data.getCurrentState() != HenshinState.INACTIVE;
    }

    /**
     * 获取当前玩家的骑士名称
     */
    public String getCurrentRiderName(Player player) {
        PlayerDataManager data = PlayerDataManager.get(player);
        return data.getActiveRiderName();
    }

    /**
     * 强制解除所有玩家的变身状态
     */
    public void forceDeactivateAll(Player player) {
        PlayerDataManager data = PlayerDataManager.get(player);
        HenshinState currentState = data.getCurrentState();

        if (currentState != HenshinState.INACTIVE) {
            String riderName = data.getActiveRiderName();
            BaseRiderConfig config = RiderConfigRegistry.getConfig(riderName);

            if (config instanceof FullRiderConfig) {
                ((FullRiderConfig) config).handleDeactivation(player);
            }
        }
    }

    /**
     * 检查玩家是否穿着指定骑士的腰带
     */
    public boolean isWearingBelt(Player player, String riderName) {
        BaseRiderConfig config = RiderConfigRegistry.getConfig(riderName);
        if (config == null) return false;

        ItemStack legItem = player.getItemBySlot(EquipmentSlot.LEGS);
        return !legItem.isEmpty() && legItem.getItem() == config.getBeltItem();
    }
}